1437D - Minimal Height Tree - CodeForces Solution


graphs greedy shortest paths trees *1600

Please click on ads to support us..

Python Code:

t = int(input())

while(t > 0):
	n = int(input())
	a = list(map(int, input().split()))
	grafo = [1, 1]
	i = 2
	j = 1
	while(i < n):
		filho = a[i-1]
		if(a[i] < filho):
			grafo.append(1)
			j += 1
		else:
			grafo[j] += 1
		i += 1
	
	i = 0
	s = 0
	lim = 1
	prof = 0
	while(i < j):
		if(i+lim <= j):
			for k in range(i, i+lim):
				s += grafo[k]
			prof += 1
		i += lim
		lim = s
		s = 0
	
	print(prof)
	t -= 1
   	   		   		      	 	    			

C++ Code:

# include <bits/stdc++.h>
# define ll long long
# define all(x) x.begin(),x.end()

using namespace std;

void solve() {
    int n , par = 0 ; cin >> n ;
    vector<int> p(n) , dis(n, 1e6) ;
    for (int i = 0; i < n; ++i) {
        cin >> p[i] ;
        p[i]-- ;
    }
    vector<vector<int>> G(n) ;
    int last = p[1] ;
    G[p[par]].push_back(last) ;
    for (int i = 2; i < n; ++i) {
        if (p[i] < last ){
            par++ ;
        }
        G[p[par]].push_back(p[i]) ;
        last = p[i] ;
    }
    queue<int> q ;
    dis[0] = 0 ;
    q.push(0) ;
    while ( !q.empty() ){
        auto cur = q.front() ;
        q.pop() ;
        for ( auto &v : G[cur] ){
            if ( dis[v] > dis[cur] + 1 ){
                dis[v] = dis[cur] + 1 ;
                q.push(v) ;
            }
        }
    }
    cout << *max_element(all(dis)) << '\n' ;
}

int main() {
    cin.tie(nullptr), cout.tie(nullptr), iostream::sync_with_stdio(false) ;
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
#endif
    int t = 1; cin >> t ;
    while (t--)
        solve();
    return 0;
}
 	 	  	 	  					  	  			   	


Comments

Submit
0 Comments
More Questions

292B - Network Topology
1339A - Filling Diamonds
910A - The Way to Home
617A - Elephant
48A - Rock-paper-scissors
294A - Shaass and Oskols
1213A - Chips Moving
490A - Team Olympiad
233A - Perfect Permutation
1360A - Minimal Square
467A - George and Accommodation
893C - Rumor
227B - Effective Approach
1534B - Histogram Ugliness
1611B - Team Composition Programmers and Mathematicians
110A - Nearly Lucky Number
1220B - Multiplication Table
1644A - Doors and Keys
1644B - Anti-Fibonacci Permutation
1610A - Anti Light's Cell Guessing
349B - Color the Fence
144A - Arrival of the General
1106A - Lunar New Year and Cross Counting
58A - Chat room
230A - Dragons
200B - Drinks
13A - Numbers
129A - Cookies
1367B - Even Array
136A - Presents